<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2023/7/7
 * Time: 14:53
 */

namespace app\api\controller;

use think\Db;

class Serve extends Base
{
    public $user_id;
    public $create_time;
    public $page;

    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $this->user_id = input('user_id');
        $this->page = input('page') ? input('page') : 1;
        $this->create_time = date('Y-m-d H:i:s');
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($this->user_id, $time, $value, $reqKey);
        if($auth == 112){
            echo json_encode(['status' => 301, 'msg' => $this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }elseif($auth == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->del]);
            exit;
        }
    }

    /*
     * 提交服务申请
     * have_store      是否有店铺    1 有   2 无
     * province        省ID
     * city            市ID
     * district        区ID
     * address         详细地址
     * user_name       联系人
     * user_phone      联系方式
     * activity_intro  活动介绍
     * begin_date      活动/开店日期
     * @return \think\response\Json
     */
    public function commitServeOrder(){
        $serve_have_store = input('have_store'); // 1 有   2 无
        $serve_province = input('province');
        $serve_city = input('city');
        $serve_district = input('district');
        $serve_address = input('address');
        $serve_user_name = input('user_name');
        $serve_user_phone = input('user_phone');
        $serve_activity_intro = input('activity_intro');
        $serve_begin_date = input('begin_date');

        if(!$this->user_id) return json(['status' => 0, 'msg' => '请先登录']);

        $number = 'GD_' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
        $insert = [
            'serve_user_id' => $this->user_id,
            'serve_number' => $number,
            'serve_have_store' => $serve_have_store,
            'serve_province' => $serve_province,
            'serve_city' => $serve_city,
            'serve_district' => $serve_district,
            'serve_address' => $serve_address,
            'serve_user_name' => $serve_user_name,
            'serve_user_phone' => $serve_user_phone,
            'serve_activity_intro' => $serve_activity_intro,
            'serve_begin_date' => $serve_begin_date,
            'serve_commit_time' => $this->create_time
        ];
        $res = Db::table('up_serve')->insert($insert);
        if($res){
            return json(['status' => 200, 'msg' => '提交成功']);
        }else{
            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
        }
    }

    /*
     * 服务工单列表
     * page     页码
     * type     1 用户   2 老师
     * serve_status   0 全部  1 待接单   3 已接单  5 待评价  6 待提点  7 已完成
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function serveOrderList(){
        $user_type = input('type'); // 1 用户  2 老师
        $serve_status = input('serve_status'); // 0 全部  1 待接单   3 已接单  5 待评价  6 待提点  7 已完成
        $where = [];

        if($user_type == 1){
            $where['serve_user_id'] = $this->user_id;
        }else{
            $where['serve_worker'] = $this->user_id;
        }
        if($serve_status != 0){
            if($serve_status == 1){
                $where['serve_status'] = ['BETWEEN', [1, 2]];
            }elseif ($serve_status == 3){
                $where['serve_status'] = ['BETWEEN', [3, 4]];
            }else{
                $where['serve_status'] = $serve_status;
            }
        }

        $data = Db::table('up_serve')
            ->join('up_u_user u1', 'u1.user_id = serve_user_id', 'LEFT')
            ->join('up_u_user u2', 'u2.user_id = serve_worker', 'LEFT')
            ->join('up_area ua1', 'serve_province = ua1.district_id', 'LEFT')
            ->join('up_area ua2', 'serve_city = ua2.district_id', 'LEFT')
            ->join('up_area ua3', 'serve_district = ua3.district_id', 'LEFT')
            ->field([
                'serve_id',
                'serve_have_store',
                'concat(ua1.district, ua2.district, ua3.district, serve_address) address',
                'serve_user_name',
                'serve_user_phone',
                'serve_activity_intro',
                'serve_begin_date',
                'serve_commit_time',
                'u1.user_real_name',
                'u1.user_phone',
                'u2.user_username worker_name',
                'u2.user_phone worker_phone',
                'serve_number',
                'serve_status'
            ])
            ->where($where)
            ->page($this->page, 10)
            ->order('serve_commit_time desc')
            ->select();
        if($data){
            return json(['status' => 200, 'msg' => $data]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /*
     * 服务工单列表---管理员端
     * page     页码
     * serve_status   0 全部  1 已提交待分配  2 已分配待接单  3 已分配已拒绝   4 已分配已同意   5 已服务待评价  6 已评价待提点   7 已完成    8 已撤销
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function serveOrderAdminList(){
        $serve_status = input('serve_status'); // 0 全部  1 已提交待分配  2 已分配待接单  3 已分配已拒绝   4 已分配已同意   5 已服务待评价  6 已评价待提点   7 已完成    8 已撤销
        $start_time = input('start_time');
        $end_time = input('end_time');
        $number = input('number');
        $commit_user_keyword = input('commit_user_keyword');
        $where = [];

        if($serve_status != 0){
            $where['serve_status'] = $serve_status;
        }
        if(isset($number) && $number != ''){
            $where['serve_number'] = ['like', '%' . $number . '%'];
        }
        if(isset($commit_user_keyword) && $commit_user_keyword != ''){
            $where['u1.user_real_name|u1.user_phone'] = ['like', '%' . $commit_user_keyword . '%'];
        }
        if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time != ''){
            $where['serve_commit_time'] = ['between', [$start_time, $end_time]];
        }
        if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time == ''){
            $where['serve_commit_time'] = ['>=', $start_time];
        }
        if(isset($start_time) && $start_time == '' && isset($end_time) && $end_time != ''){
            $where['serve_commit_time'] = ['<=', $end_time];
        }

        $data = Db::table('up_serve')
            ->join('up_u_user u1', 'u1.user_id = serve_user_id', 'LEFT')
            ->join('up_u_user u2', 'u2.user_id = serve_worker', 'LEFT')
            ->join('up_area ua1', 'serve_province = ua1.district_id', 'LEFT')
            ->join('up_area ua2', 'serve_city = ua2.district_id', 'LEFT')
            ->join('up_area ua3', 'serve_district = ua3.district_id', 'LEFT')
            ->field([
                'serve_id',
                'serve_have_store',
                'concat(ua1.district, ua2.district, ua3.district, serve_address) address',
                'serve_user_name',
                'serve_user_phone',
                'serve_activity_intro',
                'serve_begin_date',
                'serve_commit_time',
                'u1.user_real_name',
                'u1.user_phone',
                'u2.user_username worker_name',
                'u2.user_phone worker_phone',
                'serve_number',
                'serve_status'
            ])
            ->where($where)
            ->page($this->page, 10)
            ->order('serve_commit_time desc')
            ->select();
        if($data){
            return json(['status' => 200, 'msg' => $data]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /*
     * 服务人员列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function serveUserList(){
        $keyword = input('keyword');
        $where['user_status'] = 1;
        $where['user_serve_rule'] = 1;
        if($keyword){
            $where['user_real_name|user_phone'] = ['LIKE', '%' . $keyword . '%'];
        }
        $user = Db::table('up_u_user')
            ->where($where)
            ->field('user_id, user_username, user_phone, user_real_name')
            ->select();
        if($user){
            return json(['status' => 200, 'msg' => $user]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /*
     * 分配服务人员
     * serve_user_id     服务人员ID
     * serve_id          服务工单ID
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function chooseServeUser(){
        $serve_user_id = input('serve_user_id');
        $serve_id = input('serve_id');

        $user = Db::table('up_u_user')->where('user_id', $serve_user_id)->field('user_serve_rule')->find();
        if(!$user || ($user && $user['user_serve_rule'] == 2)) return json(['status' => 0, 'msg' => '该用户暂无服务权限']);

        $update = [
            'serve_id' => $serve_id,
            'serve_worker' => $serve_user_id,
            'serve_status' => 2,
            'serve_fp_time' => $this->create_time
        ];
        $res = Db::table('up_serve')->update($update);
        if($res){
            return json(['status' => 200, 'msg' => '分配成功']);
        }else{
            return json(['status' => 0, 'msg' => '分配失败']);
        }
    }

    /*
     * 同意/拒绝
     * serve_id     服务工单ID
     * type         3 拒绝   4 同意
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function allowOrRefuse(){
        $serve_id = input('serve_id');
        $type = input('type'); // 3 拒绝   4 同意

        $serve = $this->findServe($serve_id, 'serve_status');
        if($serve['serve_status'] != 2) return json(['status' => 0, 'msg' => '服务工单状态异常']);

        $update = [
            'serve_id' => $serve_id,
            'serve_status' => $type
        ];
        if($type == 4){
            $update['serve_accept_time'] = $this->create_time;
        } else{
            $update['serve_worker'] = 0;
        }

        $res = Db::table('up_serve')->update($update);
        if($res){
            return json(['status' => 200, 'msg' => '操作成功']);
        }else{
            return json(['status' => 200, 'msg' => '操作失败']);
        }
    }

    /*
     * 服务完成
     * serve_id     服务工单ID
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function serveOver(){
        $serve_id = input('serve_id');

        $serve = $this->findServe($serve_id, 'serve_status');
        if($serve['serve_status'] != 4) return json(['status' => 0, 'msg' => '服务工单状态异常']);

        $update = [
            'serve_id' => $serve_id,
            'serve_status' => 5,
            'serve_done_time' => $this->create_time
        ];
        $res = Db::table('up_serve')->update($update);
        if($res){
            return json(['status' => 200, 'msg' => '操作成功']);
        }else{
            return json(['status' => 0, 'msg' => '操作失败']);
        }
    }

    /*
     * 评价
     * serve_id                 服务工单ID
     * serve_produce_price      产品销售额
     * serve_jishu_price        技术销售额
     * serve_taoc_price         套餐销售额
     * serve_notc_price         其它品牌销售额
     * serve_other_price        其它销售额
     * serve_appraise_intro     评价描述
     * serve_appraise_images    图片
     * serve_star               评价项目和星级，json字符串格式[{"name":"服务态度","value":5},{"name":"业务熟练度","value":5}]
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function serveAppraise(){
        $serve_id = input('serve_id');
        $serve_produce_price = input('serve_produce_price');
        $serve_jishu_price = input('serve_jishu_price');
        $serve_taoc_price = input('serve_taoc_price');
        $serve_notc_price = input('serve_notc_price');
        $serve_other_price = input('serve_other_price');
        $serve_appraise_intro = input('serve_appraise_intro');
        $serve_appraise_images = input('serve_appraise_images');
        $serve_star = input('serve_star');

        $serve = $this->findServe($serve_id, 'serve_status');
        if($serve['serve_status'] != 5) return json(['status' => 0, 'msg' => '服务工单状态异常']);

        $total = $serve_produce_price + $serve_jishu_price + $serve_taoc_price + $serve_notc_price + $serve_other_price;
            $update = [
            'serve_id' => $serve_id,
            'serve_produce_price' => $serve_produce_price,
            'serve_jishu_price' => $serve_jishu_price,
            'serve_taoc_price' => $serve_taoc_price,
            'serve_notc_price' => $serve_notc_price,
            'serve_other_price' => $serve_other_price,
            'serve_total_price' => $total,
            'serve_appraise_intro' => $serve_appraise_intro,
            'serve_appraise_images' => $serve_appraise_images,
            'serve_star' => $serve_star,
            'serve_status' => 6,
            'serve_appraise_time' => $this->create_time
        ];
        if($serve_star){
            $star_arr = json_decode($serve_star, true);
            $arr_length = count($star_arr);
            $total_star = $arr_length * 5; // 总星数
            $star_number = array_sum(array_column($star_arr, 'value')); // 评价星数
            $serve_star_ratio = round($star_number / $total_star, 2);
        }else{
            $serve_star_ratio = 0;
        }
        $update['serve_star_ratio'] = $serve_star_ratio;

        $res = Db::table('up_serve')->update($update);
        if($res){
            return json(['status' => 200, 'msg' => '评价成功']);
        }else{
            return json(['status' => 0, 'msg' => '评价失败']);
        }
    }

    /*
     * 提点
     * serve_id             服务工单ID
     * real_produce_price   真实产品销售额
     * real_jishu_price     真实技术销售额
     * real_taoc_price      真实套餐销售额
     * real_notc_price      真实其它品牌销售额
     * real_other_price     真实其它销售额
     * produce_ratio        产品销售提成比例
     * jishu_ratio          技术销售提成比例
     * other_ratio          其它销售提成比例
     * taoc_ratio           套餐销售提成比例
     * serve_remark         提点备注
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function tc(){
        $serve_id = input('serve_id');
        $serve_real_produce_price = input('real_produce_price');
        $serve_real_jishu_price = input('real_jishu_price');
        $serve_real_taoc_price = input('real_taoc_price');
        $serve_real_notc_price = input('real_notc_price');
        $serve_real_other_price = input('real_other_price');
        $serve_produce_ratio = input('produce_ratio');
        $serve_jishu_ratio = input('jishu_ratio');
        $serve_taoc_ratio = input('taoc_ratio');
        $serve_other_ratio = input('other_ratio');
        $serve_remark = input('serve_remark');

        $serve = $this->findServe($serve_id);
        if($serve['serve_status'] != 6) return json(['status' => 0, 'msg' => '服务工单状态异常']);

        // 提成金额
        $produce_price = $serve_real_produce_price * $serve_produce_ratio;
        $jishu_price = $serve_real_jishu_price * $serve_jishu_ratio;
        $taoc_price = $serve_real_taoc_price * $serve_taoc_ratio;
        $other_price = $serve_real_other_price * $serve_other_ratio;
        $tc_price = ($produce_price * 100 + $jishu_price * 100 + $taoc_price * 100 + $other_price * 100) * $serve['serve_star_ratio'] / 10000;
        $total_price = $serve_real_produce_price + $serve_real_jishu_price + $serve_real_taoc_price + $serve_real_notc_price + $serve_real_other_price;

        $user = Db::table('up_u_user')->where('user_id', $this->user_id)->field('user_real_name')->find();
        $update = [
            'serve_id' => $serve_id,
            'serve_real_produce_price' => $serve_real_produce_price,
            'serve_real_jishu_price' => $serve_real_jishu_price,
            'serve_real_taoc_price' => $serve_real_taoc_price,
            'serve_real_notc_price' => $serve_real_notc_price,
            'serve_real_other_price' => $serve_real_other_price,
            'serve_real_total_price' => $total_price,
            'serve_produce_ratio' => $serve_produce_ratio,
            'serve_jishu_ratio' => $serve_jishu_ratio,
            'serve_taoc_ratio' => $serve_taoc_ratio,
            'serve_other_ratio' => $serve_other_ratio,
            'serve_remark' => $serve_remark,
            'serve_td_price' => $tc_price,
            'serve_status' => 7,
            'serve_over_time' => $this->create_time,
            'serve_tc_user_id' => $user['user_real_name']
        ];

        $serve_user = Db::table('up_u_user')->where('user_id', $serve['serve_worker'])->find();

        Db::startTrans();
        try{
            // 更新服务工单
            Db::table('up_serve')->update($update);

            // 用户佣金提成
            $this->insertBoFy($serve['serve_worker'], $serve['serve_user_id'], $serve['serve_worker'], 0, 1, '服务费提点', 1, $tc_price, $serve_user['user_bo_fy_balance'], 0, 2, 0);

            // 用户佣金
            Db::table('up_u_user')
                ->where('user_id', $serve['serve_worker'])
                ->inc('user_bo_fy_balance', $tc_price)
                ->inc('user_bo_total_fy_balance', $tc_price)
                ->update();

            Db::commit();
            return json(['status' => 200, 'msg' => '操作成功']);
        }catch (\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /*
     * 撤销
     * serve_id    服务工单ID
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function serveCancel(){
        $serve_id = input('serve_id');

        $serve = $this->findServe($serve_id, 'serve_status');
        if($serve['serve_status'] != 1 && $serve['serve_status'] != 2) return json(['status' => 0, 'msg' => '该服务工单暂不可撤销']);

        $update = [
            'serve_id' => $serve_id,
            'serve_status' => 8,
            'serve_cancel_time' => $this->create_time
        ];
        $res = Db::table('up_serve')->update($update);
        if($res){
            return json(['status' => 200, 'msg' => '操作成功']);
        }else{
            return json(['status' => 0, 'msg' => '操作失败']);
        }
    }

    /*
     * 服务工单详情
     * serve_id     服务工单ID
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function showServe(){
        $serve_id = input('serve_id');
        $data = Db::table('up_serve')
            ->join('up_u_user u1', 'u1.user_id = serve_user_id', 'LEFT')
            ->join('up_u_user u2', 'u2.user_id = serve_worker', 'LEFT')
            ->join('up_area ua1', 'serve_province = ua1.district_id', 'LEFT')
            ->join('up_area ua2', 'serve_city = ua2.district_id', 'LEFT')
            ->join('up_area ua3', 'serve_district = ua3.district_id', 'LEFT')
            ->field([
                'serve_id',
                'serve_have_store',
                'concat(ua1.district, ua2.district, ua3.district, serve_address) address',
                'serve_user_name',
                'serve_user_phone',
                'serve_activity_intro',
                'serve_begin_date',
                'serve_commit_time',
                'u1.user_real_name',
                'u1.user_phone',
                'u2.user_username worker_name',
                'u2.user_phone worker_phone',
                'serve_status',
                'serve_produce_price',
                'serve_jishu_price',
                'serve_taoc_price',
                'serve_notc_price',
                'serve_other_price',
                'serve_total_price',
                'serve_appraise_intro',
                'serve_appraise_images',
                'serve_star',
                'serve_real_produce_price',
                'serve_real_jishu_price',
                'serve_real_taoc_price',
                'serve_real_notc_price',
                'serve_real_other_price',
                'serve_real_total_price',
                'serve_produce_ratio',
                'serve_jishu_ratio',
                'serve_taoc_ratio',
                'serve_other_ratio',
                'serve_star_ratio',
                'serve_remark',
                'serve_td_price',
                'serve_fp_time',
                'serve_accept_time',
                'serve_done_time',
                'serve_appraise_time',
                'serve_over_time',
                'serve_number',
                'serve_cancel_time'
            ])
            ->where('serve_id', $serve_id)
            ->find();
        if($data['serve_star']){
            $data['serve_star'] = json_decode($data['serve_star'], true);
        }else{
            $data['serve_star'] = [];
        }
        if($data['serve_appraise_images']){
            $data['serve_appraise_images'] = explode(',', $data['serve_appraise_images']);
        }else{
            $data['serve_appraise_images'] = [];
        }

        return json(['status' => 200, 'msg' => $data]);
    }

    /*
     * 评价星级项目
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function appraiseStar(){
        $star = Db::table('up_star')->where('star_status', 1)->field('star_id, star_name')->select();
        if($star){
            return json(['status' => 200, 'msg' => $star]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /*
     * 服务费比例&服务金额
     * @return \think\response\Json
     */
    public function serveRatio(){
        $serve_id = input('serve_id');
        $field = 'serve_produce_price, serve_jishu_price, serve_taoc_price, serve_notc_price, serve_other_price, serve_total_price, serve_star_ratio';
        $serve = $this->findServe($serve_id, $field);
        $product_ratio = Db::table('up_bo_fy_config')->where('bfc_id', 37)->value('bfc_content');
        $jishu_ratio = Db::table('up_bo_fy_config')->where('bfc_id', 38)->value('bfc_content');
        $taoc_ratio = Db::table('up_bo_fy_config')->where('bfc_id', 18)->value('bfc_content');
        $other_ratio = Db::table('up_bo_fy_config')->where('bfc_id', 39)->value('bfc_content');
        $td = ($serve['serve_produce_price'] * $product_ratio + $serve['serve_jishu_price'] * $jishu_ratio + $serve['serve_taoc_price'] * $taoc_ratio + $serve['serve_other_price'] * $other_ratio) / 100 * $serve['serve_star_ratio'];
        $ratio = [
            'serve' => $serve,
            'product_ratio' => $product_ratio,
            'jishu_ratio' => $jishu_ratio,
            'taoc_ratio' => $taoc_ratio,
            'other_ratio' => $other_ratio,
            'td' => $td
        ];

        return json(['status' => 200, 'msg' => $ratio]);
    }

    // *********************************************   公共

    /*
     * 服务工单信息
     * @param $serve_id   服务工单ID
     * @param $field      字段
     * @return array|bool|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function findServe($serve_id, $field = '*'){
        $serve = Db::table('up_serve')->where('serve_id', $serve_id)->field($field)->find();
        return $serve;
    }
}